package com.haizhi.mongo;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoCursor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bson.Document;

/**
 * Created with IntelliJ IDEA.
 * Description: MongoDB游标
 * User: youfeng
 * Date: 2018-06-27
 * Time: 10:27
 */
public class ScanIter {

    private static final Logger logger = LogManager.getLogger(ScanIter.class);


    //最小被初始化的时间间隔 毫秒
    private static final int MIN_INIT_TIME_INTERVAL = 60 * 1000;

    private Document filter;
    private MongoCollection<Document> collection;
    private MongoCursor<Document> mongoCursor;

    //记录上一次初始化的时间
    private long lastInitTime;

    public ScanIter(MongoCollection<Document> collection, Document filter) {
        this.collection = collection;
        this.filter = filter;

        //根据过滤规则获得游标
        mongoCursor = initIter();
    }

    private MongoCursor<Document> initIter() {
        lastInitTime = System.currentTimeMillis();
        //根据过滤规则获得游标
        FindIterable<Document> findIterable = collection.find(filter).batchSize(50).noCursorTimeout(true);
        return findIterable.iterator();
    }

    private void reInitIter() {
        close();
        mongoCursor = initIter();
        logger.info("初始化游标...");
    }

    public void close() {
        if (null != mongoCursor) {
            mongoCursor.close();
        }
    }

    private Document getNext() {
        try {
            if (mongoCursor.hasNext()) {
                return mongoCursor.next();
            }
        } catch (Exception e) {
            logger.error("游标获取数据异常:", e);
        }

        return null;
    }

    //获得下一个数据
    public Document getNextDocument() {
        Document next = getNext();
        if (next != null) {
            return next;
        }

        //判断是否已经达到最小初始化时间间隔了
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastInitTime < MIN_INIT_TIME_INTERVAL) {
            return null;
        }

        //记录最后初始化时间
        lastInitTime = currentTime;

        reInitIter();
        next = getNext();
        return next;
    }
}
